<template>
	<view class="container">
		<!-- 主要内容区域 -->
		<view class="main-content">
			<!-- 新的左右分栏布局 -->
			<view class="content-layout">
				<!-- 左侧：缩小的canvas区域 -->
				<view class="canvas-section">
					<view v-show="canAct" class="image-container">
						<swiper class="swiper" style="height: 100%;" circular :indicator-dots="true" :autoplay="false"
							:interval="3000" :duration="300" @change="onSwiperChange">
							<swiper-item v-for="(item, index) in swiperData" :key="index">
								<canvastest-swiper :ref="`canvasSwiper${index}`" :list="item.list" :imgurl="item.imgurl"
									:swiperIndex="index" :attachs="correctionAttachs" @updateList="handleUpdateList"
									@reasonData="handleReasonData" @addErrorZi="handleAddErrorZi"></canvastest-swiper>
							</swiper-item>
						</swiper>
					</view>
				</view>

				<!-- 右侧：批改结果详情 -->
				<view class="reason-section">
					<view class="reason-container">
						<!-- 新增：分数显示区域 -->
						<view class="score-section">
							<view class="score-display" @tap="startEditScore">
								<text class="score-text">{{ score }}分</text>
							</view>
						</view>

						<view class="reason-title">批改详情</view>

						<!-- 优美句子 -->
						<view v-if="currentReasonData.goodSentences && currentReasonData.goodSentences.length > 0"
							class="reason-category">
							<view class="category-title good-title">优美句子</view>
							<view v-for="(item, index) in currentReasonData.goodSentences" :key="index" class="reason-item ">
								<view class="reason-number good-number">{{ index + 1 }}. {{ item.reason }}</view>
								<!-- <view class="reason-content">
									<view class="reason-text">{{ item.reason }}</view>
								</view> -->
							</view>
						</view>

						<!-- 修辞句子 -->
						<!-- 	<view
							v-if="currentReasonData.rhetoricalSentences && currentReasonData.rhetoricalSentences.length > 0"
							class="reason-category">
							<view class="category-title rhetorical-title">修辞手法</view>
							<view v-for="(item, index) in currentReasonData.rhetoricalSentences"
								:key="'rhetorical-' + index" class="reason-item">
								<view class="reason-number rhetorical-number">{{ index + 1 }}. {{ item.reason }}</view>
							</view>
						</view> -->

						<!-- 不雅句子 -->
						<view v-if="currentReasonData.errorSentences && currentReasonData.errorSentences.length > 0"
							class="reason-category">
							<view class="category-title error-title">需要改进</view>
							<view v-for="(item, index) in currentReasonData.errorSentences" :key="index"
								class="reason-item error-item">
								<view class="reason-number" style="color: #1E90FF;">{{ index + 1 }}.{{ item.reason }}
								</view>
							</view>
						</view>

						<!-- 如果没有数据显示提示 -->
						<view v-if="!hasReasonData" class="no-data">
							<text class="no-data-text">暂无批改详情</text>
						</view>
					</view>
				</view>
			</view>
			<view class="comment" style="padding: 20rpx;">
				<view class="teacherComments" style="font-weight: 600;font-size: 32rpx;margin-bottom: 20rpx;color: #333333;">
					教师评语
				</view>
				<view class="lvse">
					<view class="comment-content">
						<textarea class="comment-textarea" v-model="teacherComment" placeholder="请输入教师评语..."
							:maxlength="200"></textarea>
						<!-- <view class="comment-counter">{{ teacherComment.length }}/500</view> -->
					</view>
					<view class="f f-a-c f-j-b" style="height: 100rpx;width: 100%;">
						<view @click="AIPing" class="f f-a-c f-j-c"
							style="width: 216rpx;height: 68rpx;background: #4E95FF;border-radius: 10rpx;font-weight: 500;font-size: 28rpx;color: #FFFFFF;">
							AI评语生成
						</view>
						<view class="rig f f-a-c">
							<view @click="showMoBanFn" class=" f f-a-c"
								style="border: 2rpx solid #999;color: #999; border-radius: 10rpx;font-size: 28rpx;padding: 10rpx 20rpx;">
								{{ pingyuMoBan }}
								<image src="/static/home/xiala.png" style="width: 24rpx;height: 24rpx;margin-left: 10rpx;" mode="">
								</image>
							</view>
							<image src="/static/class/jia.png" @click="showAdd = true"
								style="width: 50rpx;height: 50rpx;margin-left: 20rpx;" mode=""></image>
						</view>
					</view>
				</view>
			</view>
		</view>
		<u-select v-model="showMoBan" @confirm="confirmMoBan" :list="listMoBan"></u-select>
		<u-popup v-model="showAdd" border-radius="20" mode="center">
			<view style="width: 600rpx;padding-bottom: 40rpx;">
				<view class="f f-a-c f-j-c"
					style="width: 100%;height: 70rpx;background-color: #05c490; color: #000;font-size: 32rpx;font-weight: 600;">
					新增模板
				</view>
				<view class="" style="height: 300rpx; width: 100%;">
					<view class="comment-content">
						<textarea class="comment-textarea" v-model="addTeacherComment" placeholder="请输入教师评语..."
							:maxlength="200"></textarea>
						<view class="comment-counter">{{ addTeacherComment.length }}/500</view>
					</view>
				</view>
				<view style="width: 100%;" class="f f-a-c f-j-c">
					<view @click="showAdd = false"
						style="height: 68rpx;width: 210rpx;background-color: #cccccc;color: #fff;border-radius: 34rpx;font-size: 32rpx;font-weight: 600;"
						class="f f-a-c f-j-c">
						取消
					</view>
					<view @click="comfigAdd"
						style="height: 68rpx;width: 210rpx;background-color: #05c490;color: #fff;border-radius: 34rpx;font-size: 32rpx;font-weight: 600;margin-left: 50rpx;"
						class="f f-a-c f-j-c">
						确认
					</view>
				</view>
			</view>
		</u-popup>

		<!-- 新增：分数编辑弹窗 -->
		<u-popup v-model="showScoreEdit" border-radius="20" mode="center">
			<view style="width: 500rpx;padding-bottom: 40rpx;">
				<view class="f f-a-c f-j-c"
					style="width: 100%;height: 70rpx;background-color: #C8FFE2; color: #fff;font-size: 32rpx;font-weight: 600;">
					修改分数
				</view>
				<view class="" style="height: 200rpx; width: 100%;padding: 40rpx;">
					<view style="font-size: 28rpx;color: #333;margin-bottom: 20rpx;">请输入分数（0-100）：</view>
					<input type="number" v-model="tempScore" placeholder="请输入分数"
						style="width: 90%;height: 80rpx;border: 2rpx solid #ddd;border-radius: 10rpx;padding: 0 20rpx;font-size: 32rpx;"
						maxlength="5" />
				</view>
				<view style="width: 100%;" class="f f-a-c f-j-c">
					<view @click="cancelScoreEdit"
						style="height: 68rpx;width: 150rpx;background-color: #cccccc;color: #fff;border-radius: 34rpx;font-size: 28rpx;font-weight: 600;"
						class="f f-a-c f-j-c">
						取消
					</view>
					<view @click="confirmScore"
						style="height: 68rpx;width: 150rpx;background-color: #05c490;color: #fff;border-radius: 34rpx;font-size: 28rpx;font-weight: 600;margin-left: 40rpx;"
						class="f f-a-c f-j-c">
						确认
					</view>
				</view>
			</view>
		</u-popup>

		<view class="btns f f-a-c f-j-b">
			<view class="ban">
				{{ studentInfo.name || '测试学生' }} {{ studentInfo.class || '测试班级' }}<br>
				{{ $u.timeFormat(studentInfo.date, 'yyyy/mm/dd hh:MM') || '202323423' }}
			</view>
			<view @click="goCorr" class="shen f f-a-c f-j-c" :class="{ 'loading': isReviewLoading }">
				{{ isReviewLoading ? '审阅中...' : '审阅' }}
			</view>
		</view>
		<!-- 遮罩层 -->
		<view v-if="isDrawerExpanded" class="drawer-mask" @tap="collapseDrawer"></view>
	</view>
</template>

<script>
import canvastestSwiper from '@/components/canvastest-swiper.vue'
import {
	filterErrorCharsByCanvas,
	calculateCanvasStats,
	getImageUrls
} from '@/utils/correctionResults.js'
import {
	processZuowenData
} from '@/utils/zuowenCorrectUtils.js'

export default {
	components: {
		'canvastest-swiper': canvastestSwiper
	},
	data() {
		return {
			showMoBan: false,
			showAdd: false,
			listMoBan: JSON.parse(uni.getStorageSync('mobanList') || '[]'),
			canAct: true,
			// 当前显示的轮播索引
			currentSwiperIndex: 0,
			// 轮播数据，使用真实的批改数据
			swiperData: [],

			// 抽屉状态
			isDrawerExpanded: false,
			drawerHeight: 190, // 初始抽屉高度
			minDrawerHeight: 190,
			maxDrawerHeight: 600,
			addTeacherComment: '',
			// 触摸相关
			touchStartY: 0,
			initialDrawerHeight: 0,

			// 新增：分数相关数据
			score: 85, // 当前分数
			isEditingScore: false, // 是否正在编辑分数
			showScoreEdit: false, // 显示分数编辑弹窗
			tempScore: '', // 临时分数（编辑时使用）

			// 新增：审阅按钮节流控制
			isReviewLoading: false, // 审阅按钮加载状态

			// 学生数据
			results: {
				correct: 10,
				wrong: 10,
				missing: 10
			},
			pingyuMoBan: '',
			studentInfo: {
				name: '小明',
				class: '3年2班',
				date: '20232423'
			},

			// 错误详情列表
			errorList: [],

			// 改进建议
			suggestions: [
				'加强基本笔画练习，特别是横、竖、撇、捺的书写',
				'注意字体结构的平衡，左右结构字要注意比例',
				'提高书写速度的同时保持字迹工整',
				'多练习常用偏旁部首的标准写法'
			],

			// 接收的导航数据
			navigationData: null,
			correctionData: null,
			correctionAttachs: null, // 添加attachs数据

			// 完整的原始数据（用于回传）
			originalData: null,

			// 新增的评语相关数据
			activeTab: 'correction',
			teacherComment: '',

			// 新增的批改结果相关数据
			currentReasonData: {
				goodSentences: [],
				rhetoricalSentences: [],
				errorSentences: []
			},
			hasReasonData: true
		}
	},
	computed: {
		// 当前页面的统计信息
		currentStats() {
			if (this.swiperData[this.currentSwiperIndex]) {
				return this.swiperData[this.currentSwiperIndex].stats
			}
			return {
				correct: 0,
				incorrect: 0,
				missing: 0
			}
		}
	},
	watch: {
		isDrawerExpanded(newl, oldl) {
			if (newl) {
				this.canAct = false
			} else {
				setTimeout(() => {
					this.canAct = true
				}, 300)
			}
		}
	},
	onLoad: async function (options) {
		console.log('页面加载参数:', options);

		this.pingyuMoBan = '请选择'
		// 接收从compositionList传递的数据
		if (options.data) {
			try {
				this.navigationData = JSON.parse(decodeURIComponent(options.data));
				console.log('接收到的导航数据:', this.navigationData);

				// 检查数据完整性
				if (!this.navigationData.correctionData || !this.navigationData.correctionData.aiCorrectResult) {
					console.error('缺少必要的批改数据');
					throw new Error('缺少必要的批改数据');
				}

				// 临时测试：检查传递的数据格式
				console.log('==== 数据格式检查 ====');
				console.log('aiCorrectResult类型:', typeof this.navigationData.correctionData.aiCorrectResult);
				console.log('aiCorrectResult前100字符:',
					this.navigationData.correctionData.aiCorrectResult.substring(0, 100));

				await this.initializeDataFromNavigation();
			} catch (error) {
				console.error('解析导航数据失败:', error);
				console.error('原始options.data:', options.data);
				this.initializeData(); // 使用默认数据初始化
			}
		} else {
			console.log('没有传递数据，使用默认数据初始化');
			this.initializeData(); // 使用默认数据初始化
		}
	},
	onShow() {
		// 每次页面显示时强制刷新canvas
		console.log('页面onShow - 强制刷新canvas组件');
		this.$nextTick(() => {
			this.forceUpdateCanvas();
		});
	},
	mounted() {
		// 移除mounted中的初始化，改为在onLoad中处理
	},
	methods: {
		// 点击选择模板
		showMoBanFn() {
			let mobanList = JSON.parse(uni.getStorageSync('mobanList') || '[]')
			this.listMoBan = mobanList
			if (!mobanList.length) {
				return this.$msg('暂无模板，请创建')
			}
			this.showMoBan = true
		},
		// 点击新增模板确认
		comfigAdd() {
			if (!this.addTeacherComment) {
				return this.$msg('请输入内容')
			}
			let mobanList = JSON.parse(uni.getStorageSync('mobanList') || '[]')
			console.log(mobanList, '111');
			// if (mobanList) {
			mobanList.push({
				label: `模板${mobanList.length + 1}`,
				value: this.addTeacherComment
			})
			uni.setStorageSync('mobanList', JSON.stringify(mobanList))
			this.showAdd = false
			// }else{
			// 表示没有
			// }
		},
		confirmMoBan(e) {
			console.log(e, '111');
			this.teacherComment = e[0].value
			this.pingyuMoBan = e[0].label
		},
		/**
		 * 使用导航数据初始化页面
		 */
		async initializeDataFromNavigation() {
			try {
				console.log('开始处理导航数据:', this.navigationData);

				// 保存完整的原始数据
				this.originalData = this.navigationData.originalData;
				console.log('保存的原始数据:', this.originalData);

				const processedData = processZuowenData(this.navigationData);
				console.log('处理后的数据:', processedData);

				// 检查生成的swiperData格式
				console.log('==== swiperData格式检查 ====');
				if (processedData.swiperData && processedData.swiperData.length > 0) {
					processedData.swiperData.forEach((pageData, index) => {
						console.log(`第${index + 1}页数据:`, pageData);
						if (pageData.list && pageData.list.length > 0) {
							pageData.list.forEach((listItem, listIndex) => {
								console.log(`  第${listIndex + 1}个列表项:`, listItem);
								if (listItem.chars && listItem.chars.length > 0) {
									listItem.chars.forEach((char, charIndex) => {
										console.log(`    字符${charIndex + 1}:`, {
											type: char.type,
											hasLocations: !!char.locations,
											locationsLength: char.locations ? char
												.locations.length : 0
										});
									});
								}
							});
						}
					});
				}

				// 从navigationData中获取并解析attachs数据
				if (this.navigationData.correctionData && this.navigationData.correctionData.attachs) {
					try {
						this.correctionAttachs = typeof this.navigationData.correctionData.attachs === 'string' ?
							JSON.parse(this.navigationData.correctionData.attachs) :
							this.navigationData.correctionData.attachs;
						console.log('解析的attachs数据:', this.correctionAttachs);
					} catch (error) {
						console.error('解析attachs失败:', error);
						this.correctionAttachs = null;
					}
				}

				// 1. 解析attachs.imageInfos，获取所有图片真实URL
				let imageUrls = [];
				if (this.correctionAttachs && Array.isArray(this.correctionAttachs.imageInfos)) {
					console.log('开始获取图片URL，imageInfos:', this.correctionAttachs.imageInfos);
					const imageInfos = this.correctionAttachs.imageInfos;
					const urlPromises = imageInfos.map(async (info, index) => {
						const imagePath = `composition/precorrect/${info.imageId}.jpg`;
						console.log(`请求第${index + 1}张图片URL:`, imagePath);
						const res = await this.$api.imageUrl({ image: imagePath });
						const url = res.code === '0000' ? res.data : '';
						console.log(`第${index + 1}张图片URL结果:`, url);
						return url;
					});
					imageUrls = await Promise.all(urlPromises);
					console.log('获取到的所有图片URL:', imageUrls);
				} else {
					console.warn('没有找到imageInfos或格式不正确:', this.correctionAttachs);
				}

				// 2. 组装swiperData，确保每一页用自己的图片
				if (imageUrls.length > 0 && processedData.swiperData) {
					console.log('开始为swiperData分配图片URL，图片数量:', imageUrls.length, '页面数量:', processedData.swiperData.length);
					processedData.swiperData.forEach((page, idx) => {
						const originalImgurl = page.imgurl;
						page.imgurl = imageUrls[idx] || imageUrls[0] || '/static/2.jpg';
						console.log(`第${idx + 1}页图片分配:`, {
							原始图片: originalImgurl,
							新图片: page.imgurl,
							图片索引: idx,
							图片URL: imageUrls[idx]
						});
					});
				} else {
					console.warn('没有获取到图片URL或swiperData为空，使用默认图片');
					// 如果没有获取到图片URL，使用默认图片
					processedData.swiperData.forEach((page, idx) => {
						page.imgurl = '/static/2.jpg';
						console.log(`第${idx + 1}页使用默认图片:`, page.imgurl);
					});
				}

				// 更新页面数据
				this.swiperData = processedData.swiperData;
				console.log('最终swiperData:', this.swiperData);

				this.studentInfo = {
					name: processedData.studentInfo.name || '未知学生',
					class: processedData.studentInfo.class || '未知班级',
					date: processedData.studentInfo.date || '未知日期'
				};
				this.correctionData = processedData.correctionData;

				// 从attachs中获取教师评语
				if (this.correctionAttachs) {
					this.teacherComment = this.correctionAttachs.pingYu || '';
					// 新增：从attachs中提取分数
					this.score = this.correctionAttachs.score || this.correctionAttachs.fenshu || 85; // 默认85分
					console.log('提取的分数:', this.score);
				}

				// 更新错误详情列表
				this.updateErrorList();

				// 更新批改结果相关数据
				this.updateReasonData();

				console.log('=== 数据初始化完成，强制更新canvas ===');
				// 使用nextTick确保DOM更新完成后再强制刷新canvas
				this.$nextTick(() => {
					console.log('强制更新canvas组件以确保正确渲染新学生数据');
					this.$forceUpdate();

					// 延迟一段时间后再次强制刷新，确保canvas完全重新渲染
					setTimeout(() => {
						this.$forceUpdate();
						console.log('延迟强制更新完成');
					}, 300);
				});

			} catch (error) {
				console.error('使用导航数据初始化失败:', error);
				this.initializeFallbackData();
			}
		},
		AIPing() {
			try {
				const attachs = typeof this.navigationData.correctionData.attachs === 'string' ?
					JSON.parse(this.navigationData.correctionData.attachs) :
					this.navigationData.correctionData.attachs;
				this.teacherComment = attachs.pingYu || '';
				console.log('加载的教师评语:', this.teacherComment);
			} catch (error) {
				console.error('解析attachs失败:', error);
				this.teacherComment = '';
			}
		},
		/**
		 * 更新错误详情列表
		 */
		updateErrorList() {
			this.errorList = [];

			if (this.correctionData && this.correctionData.errorZis) {
				this.errorList = this.correctionData.errorZis.map(error => ({
					character: error.zi,
					description: error.reason || '无详细说明'
				}));
			}

			// 限制显示数量，避免列表过长
			if (this.errorList.length > 10) {
				this.errorList = this.errorList.slice(0, 10);
			}
		},

		/**
		 * 初始化数据，从批改结果中提取数据（保留原有逻辑作为备用）
		 */
		initializeData() {
			try {
				// 获取按canvas分组的错别字数据
				const canvasDataArray = filterErrorCharsByCanvas()
				console.log('筛选出的canvas数据:', canvasDataArray)

				// 获取图片URL列表
				const imageUrls = getImageUrls()
				console.log('图片URLs:', imageUrls)

				// 计算统计信息
				const statsArray = calculateCanvasStats(canvasDataArray)
				console.log('统计信息:', statsArray)

				// 构建swiperData
				this.swiperData = canvasDataArray.map((canvasData, index) => {
					return {
						imgurl: imageUrls[index] || '/static/2.jpg', // 使用真实图片URL或默认图片
						list: canvasData,
						stats: statsArray[index] || {
							correct: 0,
							incorrect: 0,
							missing: 0
						}
					}
				})

				console.log('最终swiperData:', this.swiperData)
			} catch (error) {
				console.error('初始化数据失败:', error)
				// 如果初始化失败，使用备用数据
				this.initializeFallbackData()
			}
		},

		/**
		 * 初始化备用数据（如果真实数据加载失败）
		 */
		initializeFallbackData() {
			this.swiperData = [{
				// 第一页数据
				imgurl: '/static/2.jpg',
				list: [{
					text: "作文第1页（备用数据）",
					chars: []
				}],
				stats: {
					correct: 0,
					incorrect: 0,
					missing: 0
				}
			}]
		},

		/**
		 * 轮播切换事件
		 */
		onSwiperChange(e) {
			this.currentSwiperIndex = e.detail.current
			console.log('切换到第', this.currentSwiperIndex + 1, '页')

			// 切换页面时，触发当前页面的canvas发送reasonData
			// 这里需要等待canvas组件重新渲染和数据处理完成
			this.$nextTick(() => {
				// 如果有缓存的reason数据，直接使用
				if (this.swiperData[this.currentSwiperIndex] && this.swiperData[this.currentSwiperIndex]
					.reasonData) {
					this.currentReasonData = this.swiperData[this.currentSwiperIndex].reasonData;
					this.hasReasonData = this.currentReasonData.goodSentences.length > 0 ||
						this.currentReasonData.rhetoricalSentences.length > 0 ||
						this.currentReasonData.errorSentences.length > 0;
				} else {
					// 如果没有缓存，使用默认的reason数据
					this.updateReasonData();
				}
			});
		},

		/**
		 * 处理canvas组件的updateList事件
		 */
		handleUpdateList(cleanedList, swiperIndex) {
			console.log('更新第', swiperIndex + 1, '页的数据:', cleanedList)

			// 更新对应页面的list数据
			if (this.swiperData[swiperIndex]) {
				this.$set(this.swiperData[swiperIndex], 'list', cleanedList)

				// 重新计算统计信息
				let incorrectCount = 0
				let correctCount = 0
				let missingCount = 0

				cleanedList.forEach(item => {
					if (item.chars && Array.isArray(item.chars)) {
						item.chars.forEach(char => {
							if (char.type === 0) {
								incorrectCount++
							} else if (char.type === 1) {
								correctCount++
							} else if (char.type === -1) {
								missingCount++
							}
						})
					}
				})

				// 更新该页面的统计信息
				this.$set(this.swiperData[swiperIndex].stats, 'incorrect', incorrectCount)
				this.$set(this.swiperData[swiperIndex].stats, 'correct', correctCount)
				this.$set(this.swiperData[swiperIndex].stats, 'missing', missingCount)

				console.log(`第${swiperIndex + 1}页统计更新:`, {
					incorrect: incorrectCount,
					correct: correctCount,
					missing: missingCount
				});
			}
		},

		// 审阅按钮
		async goCorr() {
			// 节流控制：如果正在加载中，直接返回
			if (this.isReviewLoading) {
				uni.showToast({
					title: '请勿重复点击',
					icon: 'none',
					duration: 1500
				});
				return;
			}

			// 设置加载状态
			this.isReviewLoading = true;

			try {
				console.log('开始提交审阅数据...');

				if (!this.originalData) {
					uni.showToast({
						title: '数据异常，无法提交',
						icon: 'error'
					});
					// 数据异常时立即恢复按钮状态
					this.isReviewLoading = false;
					return;
				}

				// 重新构建修改后的aiCorrectResult
				const updatedAiCorrectResult = this.buildUpdatedAiCorrectResult();
				console.log('构建的新aiCorrectResult:', updatedAiCorrectResult);

				// 重新构建修改后的attachs
				const updatedAttachs = this.buildUpdatedAttachs();
				console.log('构建的新attachs:', updatedAttachs);

				// 准备提交的数据（保持原始格式）
				const submitData = {
					...this.originalData,
					// 更新修改后的字段（保持JSON字符串格式）
					aiCorrectResult: JSON.stringify(updatedAiCorrectResult),
					attachs: JSON.stringify(updatedAttachs),
					reviewStatus: 1 // 标记为已审阅
				};

				console.log('准备提交的完整数据:', submitData);

				// 调用审阅接口
				const response = await this.$api.resultReviewcCmposition(submitData);

				if (response.code == '0000') {
					uni.showToast({
						title: '审阅完成',
						icon: 'success'
					});

					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} else {
					// 如果接口失败，立即恢复按钮状态
					this.isReviewLoading = false;
					throw new Error(response.message || '提交失败');
				}

			} catch (error) {
				console.error('提交审阅失败:', error);
				// 异常情况下也要恢复按钮状态
				this.isReviewLoading = false;
				uni.showToast({
					title: '提交失败: ' + error.message,
					icon: 'error'
				});
			}

			// 3秒后恢复按钮状态（成功情况下的兜底处理）
			setTimeout(() => {
				this.isReviewLoading = false;
			}, 3000);
		},

		// 预览手写图片
		previewImage() {
			uni.previewImage({
				urls: ['/static/handwriting-practice.jpg'],
				current: 0
			});
		},

		// 抽屉触摸开始
		onDrawerTouchStart(e) {
			this.touchStartY = e.touches[0].clientY;
			this.initialDrawerHeight = this.drawerHeight;
		},

		// 抽屉触摸移动
		onDrawerTouchMove(e) {
			const currentY = e.touches[0].clientY;
			const deltaY = this.touchStartY - currentY;
			const newHeight = this.initialDrawerHeight + deltaY;

			// 限制抽屉高度范围
			if (newHeight >= this.minDrawerHeight && newHeight <= this.maxDrawerHeight) {
				this.drawerHeight = newHeight;
			}
		},

		// 抽屉触摸结束
		onDrawerTouchEnd(e) {
			// 根据最终高度决定是展开还是收起
			if (this.drawerHeight > (this.minDrawerHeight + this.maxDrawerHeight) / 2) {
				this.expandDrawer();
			} else {
				this.collapseDrawer();
			}
		},

		// 展开抽屉
		expandDrawer() {
			this.isDrawerExpanded = true;
			this.drawerHeight = this.maxDrawerHeight;
		},

		// 收起抽屉
		collapseDrawer() {
			this.isDrawerExpanded = false;
			this.drawerHeight = this.minDrawerHeight;
		},

		zhankaiSHouqi() {
			// 点击展开和收起
			if (!this.isDrawerExpanded) {
				this.expandDrawer()
			} else {
				this.collapseDrawer()
			}
		},


		/**
		 * 构建更新后的aiCorrectResult
		 */
		buildUpdatedAiCorrectResult() {
			try {
				// 解析原始的aiCorrectResult
				const originalResult = JSON.parse(this.originalData.aiCorrectResult);
				console.log('原始aiCorrectResult:', originalResult);

				// 直接使用当前的correctionData作为更新后的结果
				const updatedResult = {
					...originalResult
				};

				// 使用当前correctionData中的errorZis（已包含用户添加的错字）
				if (this.correctionData && this.correctionData.errorZis) {
					updatedResult.errorZis = this.correctionData.errorZis;
					console.log('更新后的errorZis:', updatedResult.errorZis);
				}

				return updatedResult;
			} catch (error) {
				console.error('构建aiCorrectResult失败:', error);
				// 如果解析失败，返回原始数据
				return JSON.parse(this.originalData.aiCorrectResult);
			}
		},

		/**
		 * 构建更新后的attachs
		 */
		buildUpdatedAttachs() {
			try {
				// 使用原始的attachs数据，不修改chars内容
				const originalAttachs = JSON.parse(this.originalData.attachs);
				console.log('使用原始attachs:', originalAttachs);

				// 重新计算统计信息
				let incorrectCount = 0;
				let correctCount = 0;
				let missingCount = 0;

				this.swiperData.forEach(pageData => {
					incorrectCount += pageData.stats.incorrect || 0;
					correctCount += pageData.stats.correct || 0;
					missingCount += pageData.stats.missing || 0;
				});

				// 更新attachs
				const updatedAttachs = {
					...originalAttachs,
					pingYu: this.teacherComment, // 更新教师评语
					score: this.score, // 新增：更新分数
					fenshu: this.score, // 兼容可能的字段名
					statisticsInfo: {
						...originalAttachs.statisticsInfo,
						incorrect: incorrectCount,
						correct: correctCount,
						missing: missingCount
					}
				};

				console.log('更新后的attachs:', updatedAttachs);
				return updatedAttachs;
			} catch (error) {
				console.error('构建attachs失败:', error);
				// 如果解析失败，返回原始数据并更新评语和分数
				const fallback = JSON.parse(this.originalData.attachs);
				fallback.pingYu = this.teacherComment;
				fallback.score = this.score;
				fallback.fenshu = this.score;
				return fallback;
			}
		},

		// 切换tab
		switchTab(tab) {
			this.activeTab = tab;
		},

		// 更新批改结果相关数据
		updateReasonData() {
			this.currentReasonData = {
				goodSentences: [],
				rhetoricalSentences: [],
				errorSentences: []
			};

			console.log('updateReasonData - correctionData:', this.correctionData);

			if (this.correctionData) {
				// 从goodJuZis提取优美句子
				if (this.correctionData.goodJuZis && Array.isArray(this.correctionData.goodJuZis)) {
					this.correctionData.goodJuZis.forEach(item => {
						this.currentReasonData.goodSentences.push({
							reason: item.reason,
							shangXi: item.shangXi || '优美句子'
						});
					});
				}

				// 从xiuCis提取修辞句子
				console.log('updateReasonData - xiuCis:', this.correctionData.xiuCis);
				if (this.correctionData.xiuCis && Array.isArray(this.correctionData.xiuCis)) {
					this.correctionData.xiuCis.forEach(item => {
						console.log('Processing xiuCis item:', item);
						this.currentReasonData.rhetoricalSentences.push({
							reason: item.reason,
							xiuCi: item.type || '修辞手法'
						});
					});
				}

				// 从errorJuZis提取不雅句子
				if (this.correctionData.errorJuZis && Array.isArray(this.correctionData.errorJuZis)) {
					this.correctionData.errorJuZis.forEach(item => {
						this.currentReasonData.errorSentences.push({
							reason: item.reason,
							correct: item.correct || '建议修改'
						});
					});
				}
			}

			this.hasReasonData = this.currentReasonData.goodSentences.length > 0 ||
				this.currentReasonData.rhetoricalSentences.length > 0 ||
				this.currentReasonData.errorSentences.length > 0;

			console.log('更新后的reasonData:', this.currentReasonData);
		},

		// 处理reasonData事件
		handleReasonData(reasonInfo) {
			console.log('接收到的reasonData:', reasonInfo);

			// 缓存每个页面的reason数据
			if (this.swiperData[reasonInfo.swiperIndex]) {
				this.$set(this.swiperData[reasonInfo.swiperIndex], 'reasonData', reasonInfo.data);
			}

			// 如果接收到的数据是当前显示页面的数据，就更新显示
			if (reasonInfo.swiperIndex === this.currentSwiperIndex) {
				this.currentReasonData = reasonInfo.data;
				this.hasReasonData = reasonInfo.data.goodSentences.length > 0 ||
					reasonInfo.data.rhetoricalSentences.length > 0 ||
					reasonInfo.data.errorSentences.length > 0;

				console.log('更新当前页面的reasonData显示:', this.currentReasonData);
			}
		},

		// 处理字符编辑事件
		handleAddErrorZi(errorZiData) {
			console.log('接收到添加错字事件:', errorZiData);

			// 将错字数据添加到correctionData.errorZis中
			if (!this.correctionData) {
				this.correctionData = {};
			}
			if (!this.correctionData.errorZis) {
				this.correctionData.errorZis = [];
			}

			// 检查是否已经存在相同位置的错字记录
			const existingErrorIndex = this.correctionData.errorZis.findIndex(error =>
				error.ziIndex === errorZiData.ziIndex &&
				error.swiperIndex === errorZiData.swiperIndex
			);

			if (existingErrorIndex !== -1) {
				// 更新现有记录
				this.correctionData.errorZis[existingErrorIndex] = errorZiData;
				console.log('已更新错字记录:', errorZiData);
			} else {
				// 添加新记录
				this.correctionData.errorZis.push(errorZiData);
				console.log('已添加错字记录:', errorZiData);
			}

			// 重新处理数据并更新对应页面的swiperData
			this.updateSwiperDataWithNewError(errorZiData);

			// 显示成功提示
			uni.showToast({
				title: `已将"${errorZiData.zi}"标记为错字`,
				icon: 'success',
				duration: 2000
			});
		},

		// 更新swiperData以包含新的错字数据
		updateSwiperDataWithNewError(errorZiData) {
			if (!this.swiperData[errorZiData.swiperIndex]) {
				return;
			}

			// 将错字数据转换为canvas组件能识别的格式
			const pageData = this.swiperData[errorZiData.swiperIndex];

			// 创建一个纯粹的错别字数据，只包含必要字段，避免触发其他渲染逻辑
			const newChar = {
				zi: errorZiData.zi,
				correct: errorZiData.correct, // 正确的字
				type: "错别字", // 明确标记为错别字
				code: errorZiData.code,
				locations: errorZiData.locations, // 使用包含imageIndex的标准locations格式
				ziIndex: errorZiData.ziIndex
				// 不添加reason、xiuCi、shangXi等字段，避免被误判为其他类型
			};

			// 如果list不存在，创建一个
			if (!pageData.list || pageData.list.length === 0) {
				pageData.list = [{
					chars: [newChar]
				}];
			} else {
				// 添加到第一个list项的chars中
				if (!pageData.list[0].chars) {
					pageData.list[0].chars = [];
				}

				// 检查是否已存在相同位置的字符，如果存在则更新，否则添加
				const existingCharIndex = pageData.list[0].chars.findIndex(char =>
					char.ziIndex === newChar.ziIndex
				);

				if (existingCharIndex !== -1) {
					// 更新现有字符
					pageData.list[0].chars[existingCharIndex] = newChar;
					console.log(`更新了第${errorZiData.swiperIndex + 1}页的现有错字:`, newChar);
				} else {
					// 添加新字符
					pageData.list[0].chars.push(newChar);
					console.log(`添加了第${errorZiData.swiperIndex + 1}页的新错字:`, newChar);
				}
			}

			// 更新统计信息
			if (!pageData.stats) {
				pageData.stats = {
					correct: 0,
					incorrect: 0,
					missing: 0
				};
			}

			// 重新计算错别字数量（type === "错别字"）
			pageData.stats.incorrect = pageData.list[0].chars.filter(char => char.type === "错别字").length;

			console.log(`更新了第${errorZiData.swiperIndex + 1}页的数据:`, {
				新增错字: newChar,
				当前页错字总数: pageData.stats.incorrect
			});
			// 强制触发页面重新渲染
			this.$forceUpdate();
		},
		startEditScore() {
			this.isEditingScore = true;
			this.showScoreEdit = true;
			this.tempScore = this.score.toString();
		},
		confirmScore() {
			const scoreValue = parseInt(this.tempScore);
			if (!this.tempScore) {
				uni.showToast({
					title: '请输入分数',
					icon: 'error'
				});
				return;
			}
			if (isNaN(scoreValue) || scoreValue < 0 || scoreValue > 100) {
				uni.showToast({
					title: '分数范围为0-100',
					icon: 'error'
				});
				return;
			}

			this.score = scoreValue;
			this.isEditingScore = false;
			this.showScoreEdit = false;

			uni.showToast({
				title: '分数修改成功',
				icon: 'success'
			});
		},
		cancelScoreEdit() {
			this.isEditingScore = false;
			this.showScoreEdit = false;
		},
		forceUpdateCanvas() {
			// 强制刷新canvas组件
			console.log('开始强制更新所有canvas组件');

			// 先强制Vue组件更新
			this.$forceUpdate();

			// 调用每个canvas组件的强制重新初始化方法
			this.$nextTick(() => {
				if (this.swiperData && this.swiperData.length > 0) {
					this.swiperData.forEach((item, index) => {
						const canvasRef = this.$refs[`canvasSwiper${index}`];
						if (canvasRef && canvasRef[0] && canvasRef[0].forceReinitialize) {
							console.log(`强制重新初始化canvas ${index}`);
							canvasRef[0].forceReinitialize();
						}
					});
				}
			});
		}
	}
}
</script>

<style lang="scss" scoped>
.lvse {
	padding: 20rpx;
	height: 400rpx;
	background: linear-gradient(90deg, #CFFFE9 0%, #E7FAFF 100%);
	border-top-right-radius: 40rpx;
	border-top-left-radius: 40rpx;
	padding-bottom: 80rpx;
	overflow-y: auto;
}

.btns {
	position: fixed;
	height: 180rpx;
	bottom: 0;
	left: 0;
	z-index: 9999;
	background-color: #fff;
	width: 100%;
	padding: 10rpx 30rpx 30rpx;

	.ban {
		font-family: SourceHanSansCN, SourceHanSansCN;
		font-weight: 500;
		font-size: 24rpx;
		color: #333333;
	}

	.shen {
		width: 70%;
		height: 96rpx;
		background: #05C490;
		border-radius: 30rpx;
		font-family: SourceHanSansCN, SourceHanSansCN;
		font-weight: 500;
		font-size: 36rpx;
		color: #FFFFFF;
		transition: all 0.3s ease;

		&.loading {
			background: #cccccc;
			opacity: 0.6;
			pointer-events: none; // 禁用点击事件
		}
	}
}

.container {
	height: 100vh;
	background-color: #f5f5f5;
	position: relative;
	overflow: hidden;
}

.main-content {
	min-height: calc(100vh - 180rpx);
	/* 减去底部按钮高度 */
	transition: padding-bottom 0.3s ease;
}

.content-layout {
	display: flex;
	height: 800rpx;
	/* 固定高度，与swiper容器一致 */
	padding: 10rpx;
	gap: 10rpx;
	/* 左右区域之间的间距 */
	overflow: hidden;
	/* 防止内容溢出 */
}

.canvas-section {
	flex: 0 0 520rpx;
	/* 固定宽度520rpx */
	position: relative;
	background-color: #f8f9fa;
	border-radius: 12rpx;
	height: 800rpx;
	/* 固定高度 */
	overflow: hidden;
	/* 防止canvas溢出 */
}

.image-container {
	position: relative;
	height: 100%;
	/* 占满父容器高度 */
	overflow: hidden;
	/* 防止内容溢出 */
}

.swiper {
	height: 100% !important;
	width: 100%;
}

.swiper-item {
	height: 100%;
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.handwriting-image {
	width: 100%;
	border-radius: 12rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.reason-section {
	flex: 1;
	/* 占据剩余空间 */
	position: relative;
	height: 800rpx;
	/* 固定高度，与左侧一致 */
	overflow-y: auto;
	/* 内容过多时可滚动 */
	background-color: #ffffff;
	border-radius: 12rpx;
}

.reason-container {
	padding: 8rpx;
	// background-color: white;
	// border-radius: 12rpx;
	// box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.reason-title {
	font-size: 24rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 15rpx;
}

.reason-category {
	margin-bottom: 20rpx;
}

.category-title {
	font-size: 24rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 8rpx;
}

.reason-item {
	display: flex;
	align-items: center;
	margin-bottom: 8rpx;
}

.reason-number {
	color: #ff4757;
	font-size: 16rpx;
	line-height: 1.3;
}

.reason-content {
	flex: 1;
	font-size: 26rpx;
	color: #666;
	line-height: 1.4;
}

.reason-text {
	font-size: 26rpx;
	color: #666;
	line-height: 1.4;
}

.reason-correct {
	font-size: 24rpx;
	color: #28a745;
	margin-top: 8rpx;
	padding: 4rpx 8rpx;
	background-color: #e8f5e8;
	border-radius: 8rpx;
}

.no-data {
	text-align: center;
	padding: 20rpx;
	font-size: 28rpx;
	color: #666;
}

.drawer-container {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	background-color: white;
	border-radius: 40rpx 40rpx 0 0;
	box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
	transition: height 0.3s ease;
	z-index: 1000;
}

.drawer-header {
	height: 60rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	position: relative;
	cursor: grab;
}

.drag-indicator {
	width: 60rpx;
	height: 6rpx;
	background-color: #ddd;
	border-radius: 3rpx;
}

.drawer-content {
	// background-color: #f8fffe;
	border-radius: 0 0 20rpx 20rpx;
}

.content-wrapper {
	padding: 0 30rpx 120rpx;
}

.result-title {
	// text-align: left;
	margin-bottom: 30rpx;
}

.title-text {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
}

.stats-section {
	margin-bottom: 30rpx;
	background: linear-gradient(90deg, #E8F5E8 0%, #F0FFF0 100%);
	padding: 20rpx;
	border-radius: 50rpx 50rpx 0 0;
}

.stat-item {
	display: flex;
	align-items: center;
	margin-bottom: 10rpx;
	padding: 15rpx;
	// background-color: white;
	border-radius: 12rpx;
}

.stat-icon {
	width: 40rpx;
	height: 40rpx;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 15rpx;
}

.correct-icon {
	background-color: #28a745;
}

.wrong-icon {
	background-color: #dc3545;
}

.missing-icon {
	background-color: #28a745;
}

.icon-text {
	color: white;
	font-size: 20rpx;
	font-weight: bold;
}

.stat-label {
	font-size: 28rpx;
	color: #666;
	margin-right: 10rpx;
}

.stat-value {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
}

.student-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx;
	background-color: white;
	border-radius: 12rpx;
	margin-bottom: 30rpx;
}

.student-details {
	display: flex;
	align-items: center;
}

.student-name {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	margin-right: 15rpx;
}

.student-class {
	font-size: 24rpx;
	color: #8e44ad;
	background-color: #f8f9fa;
	padding: 4rpx 12rpx;
	border-radius: 12rpx;
}

.date-info {
	font-size: 24rpx;
	color: #666;
}

.error-details,
.suggestions {
	margin-bottom: 30rpx;
}

.section-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
}

.error-item {
	display: flex;
	align-items: center;
	color: #1E90FF;
}

.error-char {
	width: 60rpx;
	height: 60rpx;
	background-color: #ff4757;
	color: white;
	border-radius: 8rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	font-weight: bold;
	margin-right: 15rpx;
}

.error-desc {
	flex: 1;
	font-size: 26rpx;
	color: #666;
	line-height: 1.4;
}

.suggestion-item {
	padding: 15rpx;
	background-color: white;
	border-radius: 12rpx;
	margin-bottom: 10rpx;
	border-left: 4rpx solid #28a745;
}

.suggestion-text {
	font-size: 26rpx;
	color: #666;
	line-height: 1.4;
}

.action-section {
	margin-top: 40rpx;
}

.review-btn {
	width: 100%;
	height: 80rpx;
	background-color: #28a745;
	color: white;
	border: none;
	border-radius: 12rpx;
	font-size: 32rpx;
	font-weight: 500;
}

.review-btn::after {
	border: none;
}

.drawer-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.3);
	z-index: 999;
}

.drawer-expanded {
	z-index: 1001;
}

.tab-container {
	margin-bottom: 30rpx;
}

.tab-bar {
	display: flex;
	border-bottom: 2rpx solid #ddd;
}

.tab-item {
	flex: 1;
	text-align: center;
	padding: 20rpx 0;
	font-size: 28rpx;
	color: #666;
	cursor: pointer;
	position: relative;
	transition: all 0.3s ease;
}

.tab-active {
	color: #28a745;
	font-weight: bold;
}

.tab-active::after {
	content: '';
	position: absolute;
	bottom: 0;
	left: 0;
	right: 0;
	height: 4rpx;
	background-color: #28a745;
	border-radius: 2rpx;
}

.tab-content {
	/* v-show控制显示隐藏，无需设置display:none */
}

.teacher-comments {
	margin-bottom: 30rpx;
	padding: 20rpx;
	background-color: white;
	border-radius: 12rpx;
}

.comment-content {
	position: relative;
}

.comment-textarea {
	width: 100%;
	height: 250rpx;
	padding: 15rpx;
	// border: 1rpx solid #28a745;
	border-radius: 8rpx;
	font-size: 26rpx;
	line-height: 1.4;
	// background-color: #fafafa;
	box-sizing: border-box;
}

.comment-counter {
	position: absolute;
	bottom: 10rpx;
	right: 15rpx;
	font-size: 22rpx;
	color: #999;
}

// 优美句子样式
.good-title {
	color: #ff0000;
}

.good-number {
	// background-color: #ff0000;
}

.good-item {
	border-left: 4rpx solid #ff0000;
}

// 修辞句子样式
.rhetorical-title {
	color: #800080;
}

.rhetorical-number {
	color: #800080;
	font-size: 16rpx;
	line-height: 1.3;
}

.rhetorical-item {
	display: flex;
	align-items: center;
	margin-bottom: 8rpx;
}

// 不雅句子样式
.error-title {
	color: #1E90FF;
}

.error-number {
	background-color: #1E90FF;
}

.score-section {
	margin-bottom: 20rpx;
}

.score-display {
	width: 130rpx;
	background-color: #ff0000;
	border-radius: 20rpx;
	padding: 10rpx 20rpx;
	color: white;
	font-size: 28rpx;
	font-weight: bold;
}

.score-text {
	font-size: 28rpx;
	font-weight: bold;
	color: white;
}

.score-tip {
	font-size: 24rpx;
	font-weight: normal;
	color: rgba(255, 255, 255, 0.8);
	margin-left: 10rpx;
}
</style>